// packagePay/pages/insurance/Insurance.js
import user from '../../../utils/user'
import {
    createDayProject
} from '../../../api/app'
import {
    guaranteedCount,
    insureListState,
    insureRecordsList,
    deleteInsuranceGsc,
    getInsuranceBillListGsc,
    getInsuranceEnterprise,
    changeInsureRecordsCount,
    getInsuranceRisk,
    everybalancehint
} from '../../api/insurance'

const app = getApp()

Page({
    /**
     * 页面的初始数据
     */
    data: {
        isPopup: true,
        tabList: [{
                title: '投保记录',
                num: '0'
            },
            {
                title: '投保账单',
                num: '0'
            }
        ],
        tabIndex: 0,
        insurePagesNum: 1,
        insurePagesSize: 20,
        recordPageNum: 1,
        recordPagesSize: 20,
        insuranceList: false,
        tipList: false,
        enter: '',
        enterId: '',
        isCreate: false,
        topInsuranceNum: {},
        insuranceRecord: [],
        recordHasNextPage: false,
        recordTotalCount: 0,
        insuranceBill: [],
        billHasNextPage: false,
        isAdmin: false,
        userId: '',
        insureType: [],
        insureCompanyType: 'insure002_gsc',
        month: '',
        condition: 0,
        x: 1000,
        successCount: 0,
        expiresCount: 0,
        isProgrammeImg: false,
        riskInfo: {},
        claimRate: ''
    },
    static: {
        recordAll: [],
        recordSuccess: [],
        recordExpires: [],
        everybalancehintflag: false,
        tcflag:false,
        canttbflag :false
    },
    async onLoad() {
        console.log(user.isForbidInsure,'user.isForbidInsure');
        wx.setStorageSync('dayInsureTcflag', user.isForbidInsure)
        this.setData({
            canttbflag:user.isForbidInsure
        })
        if (wx.getStorageSync('dayInsureTcflag')) {
            this.setData({
                tcflag: true
            })
        } else {
            this.setData({
                tcflag: false
            })
        }
        const res = await everybalancehint({
            insurCompanyType: 'insure002_gsc'
        })
        console.log(res,'11111111111111111111');
        if (res.isReminder === 1) {
            wx.showModal({
                title: '日日保余额不足',
                content: '当前余额不足' + res.wesureReminderBalance + '元，为了不影响您的后续工作，赶快去充值吧~',
                showCancel: false,
            })
        }
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onReady: function () {
        // this.setData({
        //     month: app.dateFormat('YYYY-mm',new Date())
        // })
        user.waitLogin().then(() => {
            console.log(user.insureType, 'user.insureType')
            this.setData({
                userId: user.userId,
                insureType: user.insureType,
                insureCompanyType: user.insureCompanyType ? user.insureCompanyType : 'insure002_gsc'
            }, () => {
                console.log(this.data.insureCompanyType, user.insureCompanyType, 'insureCompanyType')
            })
        })
        console.log('ready')
    },
    onShow() {
        this.setData({
            month: app.dateFormat('YYYY-mm', new Date())
        })
        console.log(this.data.isOriginal, 'isOriginal')
        this.data.insurePagesNum = 1
        this.data.recordPageNum = 1
        this.data.recordHasNextPage = false
        this.data.billHasNextPage = false
        user.waitLogin().then(() => {
            this.getGuaranteedCount()
            this.getInsureListState(true)
            this.getInsureRecordsList(true)
            this.getInsuranceRiskInfo()
        })
    },
    closetc() {
        this.setData({
            tcflag: false
        })
        wx.setStorageSync('dayInsureTcflag', false)
    },
    onNameInput(event) {
        this.setData({
            createProjectName: event.detail.value
        })
    },
    onTab(event) {
        let {
            detail
        } = event
        // if (index === 0) {
        //     console.log('关注的岗位')
        // } else {
        //     console.log('关注的店铺')
        // }
        this.setData({
            tabIndex: detail
        })
    },
    // 头部风险信息
    async getInsuranceRiskInfo() {
        const result = await getInsuranceRisk({
            coName: user.companyName,
            insureCompanyType:'insure_type_rrb'
        })
        this.setData({
            riskInfo: result,
            claimRate: 100 - (100 * (Number(((result.finalMoney / result.totalPrice) * 100).toFixed(2)) >= 140 ? 140 : Number(((result.finalMoney / result.totalPrice) * 100).toFixed(2))) / 140),
            'riskInfo.nextRate': (result.nextRate * 100),
            'riskInfo.insurRate': (result.insurRate * 100),
            'riskInfo.claimRate': Number(((result.finalMoney / result.totalPrice) * 100).toFixed(2))
        })
        console.log(this.data.claimRate, 'claimRateclaimRate')
        console.log(result, 'result')
    },
    // 头部
    getGuaranteedCount() {
        guaranteedCount({
            insureCompanyType: user.insureCompanyType
            // insure001_wesure 
        }).then(res => {
            console.log(res, 'csjres');
            this.setData({
                topInsuranceNum: res
            })
        })
    },
    // 投保账单
    getInsureListState(clear = false) {
        if (user.insureCompanyType === 'insure002_gsc') {
            getInsuranceBillListGsc({
                pageNum: this.data.insurePagesNum,
                pageSize: this.data.insurePagesSize,
                searchMonth: this.data.month,
            }).then(res => {
                console.log(res, 'resres')
                if (!res.hasNextPage) {
                    console.log('修改啦？？？？？')
                    this.setData({
                        billHasNextPage: true
                    }, () => {
                        console.log(this.data.billHasNextPage, 'this.data.billHasNextPage')
                    })
                }
                if (clear) {
                    this.data.insuranceBill = []
                }
                let temporary = []
                temporary.push(...this.data.insuranceBill)
                temporary.push(...res.list)
                console.log(temporary, 'temporary')
                this.setData({
                    insuranceBill: temporary,
                    ['tabList[1].num']: res.totalCount
                })
            })
        } else {
            insureListState({
                pageNum: this.data.insurePagesNum,
                pageSize: this.data.insurePagesSize,
                searchMonth: this.data.month,
            }).then(res => {
                console.log(res)
                if (!res.hasNextPage) {
                    this.setData({
                        billHasNextPage: true
                    })
                }
                if (clear) {
                    this.data.insuranceBill = []
                }
                let temporary = []
                temporary.push(...this.data.insuranceBill)
                temporary.push(...res.list)
                this.setData({
                    insuranceBill: temporary,
                    ['tabList[1].num']: res.totalCount
                })
            })
        }
    },
    // 投保记录
    getInsureRecordsList(clear = false) {
        insureRecordsList({
            pageNum: this.data.recordPageNum,
            pageSize: this.data.recordPagesSize,
            searchMonth: this.data.month,
            searchWesureState: ['ALL', 'SUCCESS', 'EXPIRES'][this.data.condition],
            insureCompanyType: user.insureCompanyType
        }).then(res => {
            if (!res.hasNextPage) {
                this.setData({
                    recordHasNextPage: true
                })
            }
            res.list.forEach((item, index) => {
                res.list[index].createTime = item.createTime.slice(5, 16)
            })
            console.log(res, '投保记录改变后')
            if (clear) {
                this.data.insuranceRecord = []
            }
            let temporary = []
            temporary.push(...this.data.insuranceRecord)
            temporary.push(...res.list)
            const {
                condition
            } = this.data

            this.static.recordAll = []
            this.static.recordSuccess = []
            this.static.recordExpires = []

            switch (condition) {
                case 0:
                    this.static.recordAll = temporary
                    break
                case 1:
                    this.static.recordSuccess = temporary
                    break
                case 2:
                    this.static.recordExpires = temporary
                    break
            }
            // if(condition == 0){
            //     this.static.recordAll = temporary
            // }else if(condition == 1){
            //     this.static.recordSuccess = temporary
            // }else{
            //     this.static.recordExpires = temporary
            // }
            console.log(this.static.recordAll, 'recordAll')
            this.setData({
                insuranceRecord: condition == 0 ? this.static.recordAll : condition == 1 ? this.static.recordSuccess : condition == 2 ? this.static.recordExpires : '',
                ['tabList[0].num']: res.allCount || res.totalCount,
                successCount: res.successCount,
                expiresCount: res.expiresCount
            })
        })
    },
    changeInsureRecordsCount(searchWesureState) {
        console.log(searchWesureState, 'searchWesureState')
        return changeInsureRecordsCount({
            searchMonth: this.data.month,
            searchWesureState: searchWesureState,
            insureCompanyType: user.insureCompanyType
        }).then(res => {
            return res
        })
    },
    onSetCondition(event) {
        if (Number(event.currentTarget.dataset.key) == this.data.condition) {
            this.setData({
                condition: 0
            }, () => {
                if (this.static.recordAll.length === 0) {
                    this.getInsureRecordsList(true)
                } else {
                    const alter = this.changeInsureRecordsCount('ALL')
                    alter.then(res => {
                        if (Number(res) === Number(this.data.tabList[0].num)) {
                            this.setData({
                                insuranceRecord: this.static.recordAll
                            })
                        } else {
                            this.getInsureRecordsList(true)
                        }
                    })
                }
            })
        } else {
            this.setData({
                condition: Number(event.currentTarget.dataset.key)
            }, () => {
                if (this.data.condition == 1) {
                    console.log(this.static, 'static')
                    if (this.static.recordSuccess.length === 0) {
                        this.getInsureRecordsList(true)
                    } else {
                        this.changeInsureRecordsCount('SUCCESS').then(res => {
                            if (Number(res) === this.data.successCount) {
                                this.setData({
                                    insuranceRecord: this.static.recordSuccess
                                })
                            } else {
                                this.getInsureRecordsList(true)
                            }
                        })
                    }
                    console.log('??1')
                } else if (this.data.condition == 2) {
                    if (this.static.recordExpires.length === 0) {
                        this.getInsureRecordsList(true)
                    } else {
                        this.changeInsureRecordsCount('EXPIRES').then(res => {
                            if (Number(res) === this.data.expiresCount) {
                                this.setData({
                                    insuranceRecord: this.static.recordExpires
                                })
                            } else {
                                this.getInsureRecordsList(true)
                            }
                        })
                    }
                    console.log('??2')
                }
            })
        }

    },
    // 滚动到底部 触发
    scrollDown() {
        if (this.data.tabIndex === 0) {
            if (this.data.recordHasNextPage) return
            this.setData({
                recordPageNum: this.data.recordPageNum += 1
            }, () => {
                this.getInsureRecordsList()
            })
        }
        if (this.data.tabIndex === 1) {
            console.log(this.data.billHasNextPage, '投保账单到底部啦吗')
            if (this.data.billHasNextPage) return
            this.setData({
                insurePagesNum: this.data.insurePagesNum += 1
            }, () => {
                console.log('国寿财2')
                this.getInsureListState()
            })
        }
    },
    onEnterInsurance() {
        console.log('111')
        this.setData({
            insuranceList: !this.data.insuranceList
        })
    },
    // 选择保险方案
    insuranceEnter(event) {
        console.log(event, '保险')

        setTimeout(() => {
            this.setData({
                dictLabel: event.currentTarget.dataset.label,
                dictValue: event.currentTarget.dataset.value,
                // 194
                insuranceList: !this.data.insuranceList
            }, () => {
                console.log(this.data.dictLabel, this.data.dictValue, 'dictLabel')
            })
        }, 16)

    },
    cantonCreatePorject(){
        this.setData({
            tcflag:true
        })
    },
    onCreatePorject() {
        if (!user.isOpenWesure) {
            app.toast('暂未开通微保服务，请联系工作人员开通')
            return
        }
        if (user.insureCompanyType === 'insure002_gsc') {
            wx.navigateTo({
                url: '/packageInsurance/pages/insurance-launch/insurance-launch',
            })
            return
        }
        this.setData({
            'isCreate': true
        })
        getInsuranceEnterprise({
            insureCompanyType: 'insure_type_rrb'
        }).then((res) => {
            this.setData({
                'companyList': res
            })
            return
        })
        // this.setData({
        //     'isCreate': true
        // })
        // getInsuranceEnterprise().then((res) => {
        //     this.setData({
        //         'companyList': res
        //     })
        // })
    },
    onCancelCreate() {
        this.setData({
            'isCreate': false
        })
    },
    createProject() {
        console.log(this.data.enterId, this.data.dictValue, '请选择投保企业')
        if (!this.data.enterId) {
            app.toast('请选择投保企业')
            return
        }
        if (!this.data.dictValue) {
            app.toast('请选择投保方案')
            return
        }
        console.log(this.data.dictLabel, 'serveCompanyName')
        let dictLabel = ''
        dictLabel = user.insureType.filter((item) => {
            if (item.dictValue == this.data.dictValue) {
                return item
            }
        })
        console.log(dictLabel, 'dictLabel')


        createDayProject({
            type: 4,
            wesureTypeName: dictLabel[0].dictLabel,
            wesureType: this.data.dictValue,
            serveCompanyName: this.data.enter,
            serveCompanyId: this.data.enterId,
        }).then(res => {
            app.toast('创建项目成功，正在为您跳转')
            this.setData({
                isCreate: false
            })
            if (user.insureCompanyType === 'insure001_wesure') {
                setTimeout(() => {
                    wx.navigateTo({
                        url: '/packagePay/pages/resident/resident?id=' + res
                    })
                }, 2000)
            }
            if (user.insureCompanyType === 'insure002_gsc') {
                setTimeout(() => {
                    wx.navigateTo({
                        url: '/packageInsurance/pages/insurance-insure-detail/insurance-insure-detail?id=' + res
                    })
                }, 2000)
            }
        })
    },

    tapEnter(event) {
        console.log('tapEnter', event)
        setTimeout(() => {
            this.setData({
                'enter': event.currentTarget.dataset.name,
                'enterId': event.currentTarget.dataset.id,
                tipList: false
            }, () => {
                console.log(this.data.enter, this.data.enterId, 'enter')
            })
        }, 16)

    },
    onEnterInput(event) {
        console.log(event, 'event')
        const data = []
        for (const i in this.data.companyList) {
            console.log(i, this.data.companyList[i])
            // if (this.data.companyList[i].serveCompanyName && this.data.companyList[i].serveCompanyName.indexOf(event.detail.value) !== -1) {

            // }
            data.push(this.data.companyList[i])
        }
        console.log(this.data.enter, 'datadata')
        this.setData({
            'enter': this.data.enter,
            'enterId': this.data.enterId,
            tipList: !this.data.tipList ? data : !this.data.tipList,

        }, () => {
            console.log(this.data.enter, '123tipList')
        })
    },
    onEnterInputConfirm(event) {
        this.setData({
            'enter': event.detail.value,
            tipList: false
        })
    },
    // 点击进入投保企业
    onGoEnterprise() {
        wx.navigateTo({
            url: '/pages/enterprise/enterprise?select=1&radio=1&searchOpenWesure=0',
        })
    },
    // 投保企业管理
    onGoManage() {
        if (!user.isOpenWesure) {
            app.toast('暂未开通微保服务，请联系工作人员开通')
            return
        }
        wx.navigateTo({
            url: '/packageInsurance/pages/insurance-organize/insurance-organize',
        })
    },
    // 产品介绍
    onGoPIntroduce() {
        wx.navigateTo({
            url: '/packageInsurance/pages/insurance-programme/insurance-programme',
        })
    },
    // 在线报案
    onGoPReport() {
        wx.navigateTo({
            url: '/packageInsurance/pages/insurance-report/insurance-report',
        })
    },
    onGoDetail(event) {
        const {
            id
        } = event.currentTarget.dataset
        if (user.insureCompanyType === 'insure001_wesure') {
            wx.navigateTo({
                url: '/packagePay/pages/resident/resident?id=' + id + '&cshowmore=' + true
            })
        }
        if (user.insureCompanyType === 'insure002_gsc') {
            wx.navigateTo({
                url: '/packageInsurance/pages/insurance-insure-detail/insurance-insure-detail?id=' + id + '&showmore=' + true,
            })
        }
    },
    // 充值
    onRecharge() {
        if (!user.isOpenWesure) {
            app.toast('暂未开通微保服务，请联系工作人员开通')
            return
        }
        wx.navigateTo({
            url: '/packageInsurance/pages/insurance-recharge/insurance-recharge'
        })
    },
    // 去当前在保人员
    onInInsurancePersonnel(event) {
        console.log(event, 'event')
        wx.navigateTo({
            url: '/packageInsurance/pages/insurance-current-take-effect/insurance-current-take-effect',
        })
    },
    onDeleteInsuranceGsc(event) {
        deleteInsuranceGsc({
            id: event.currentTarget.dataset.id
        }).then(() => {
            app.toast('操作成功', 'success')
            this.setData({
                x: 1000
            })
            setTimeout(() => {
                this.getInsureRecordsList(true)
            }, 1500)
        })
    },
    onInsuranceMonthChange(event) {
        this.setData({
            month: event.detail.value
        })
        this.data.billHasNextPage = false
        this.getInsureListState(true)
        this.getInsureRecordsList(true)
    },
    onToBill(event) {
        wx.navigateTo({
            url: '/packageInsurance/pages/insurance-bill-detail/insurance-bill-detail?id=' + event.currentTarget.dataset.id
        })
    },
    // 去转出页面
    goTransferOut() {
        wx.navigateTo({
            url: '/packageInsurance/pages/balance-out/balance-out?type=day',
        })
    },
    // 原价弹窗回调
    onCancelOrigina() {
        this.setData({
            isOriginal: false
        })
        console.log('回调')
    },
    // 查看原价
    onCancelOriginal() {
        this.setData({
            isProgrammeImg: true
        })
        console.log('回调')
    },
    // 关闭原价图片
    onCloseOriginal() {
        this.setData({
            isProgrammeImg: false
        })
    },
    onRead() {
        this.setData({
            isPopup: false
        })
    },
    onInsuranceRisk() {
        wx.navigateTo({
            url: '/packageInsurance/pages/insurance-risk/insurance-risk',
        })
    }
})